<?php
/**
*Customisation for new disagne
*/
/**
*Draw city block
*/
function advert_draw_city_menu($hidden=true)
{

#$current_city =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);
global $infopark;    
$current_city=$infopark->get_city_by_url();
#pre($current_city);
$vid=6;

#$citys=db_select("citydomain","c")->fi1elds("c")->orderby('c.name')->execute();
$cities=$infopark->cities_list();

$out='<div class="citydomain">';

$out.='<div>'.(($current_city)?$current_city['name']."&nbsp;":"ВСЯ УКРАИНА&nbsp;").'<span onClick="if(jQuery(\'#citymenu\').is(\':hidden\'))jQuery(\'#citymenu\').show();else jQuery(\'#citymenu\').hide();" class="citydomain_lnk arrow">&nbsp;</span></div>';
#}

$out.='<ul id="citymenu" '.($hidden?' style="display:none;"':'').'>';
#<select onchange="alert(this.value);">';
if($current_city!=false)$out.='<li>'.l('ВСЯ УКРАИНА','http://www.infopark.com.ua').'</li>';
//while($city=$citys->fetchAssoc())
foreach($cities as $city)
  {
  if($city->tid!=$current_city['tid'])  
  $out.='<li>'.l($city->name,$city->url).'</li>';
  }
  $out.='</ul>
  </div>';
return $out;  
}
/**
*Draw taxonomy left menu
*/
function advert_draw_taxonomy_menu()
{
$menu=menu_navigation_links('main-menu');

#print $is_advert."<hr>";
$out='<div>';
/*
$out.='<ul class="main-menu">';

foreach($menu as $mid=>$m)
  {

 $mid=str_replace('active-trail','active-trail active',$mid);
 if(($m['href']=='adverts')&&$is_advert){$mid.=" active-trail active";$active_class="active";}
 $out.='<li class="'.$mid.'">'.l($m['title'],$m['href'],array('attributes'=>array('class'=>$active_class))).'</li>';
 #print strstr($mid,"active")."<hr>";
  if(($m['href']=='adverts')&&strstr($mid,"active"))
    {
    $subcat_rec=db_query("SELECT ttd.* 
				  FROM taxonomy_term_data ttd 
				  LEFT JOIN `taxonomy_term_hierarchy` tth ON tth.tid=ttd.tid WHERE tth.parent=0 AND ttd.vid=12 ORDER BY ttd.weight");
	$call='';			  
    while($subcat=$subcat_rec->fetchObject())
      {
      if(empty($call))$call='<script>advert_switch_menu('.$subcat->tid.');</script>';
      $out.='<li class="subcat" id="maincat'.$subcat->tid.'"><a href="javascript://"  onClick="advert_switch_menu('.$subcat->tid.');">'.$subcat->name.'</a></li>';
      }
    }
  }
$out.='</ul>';*/

  $out.=epimetheus_main_menu_modifier(theme('links__system_main_menu', array(
				        'links' => $menu,
				        'attributes' => array(
#				            'id' => 'main-menu',
				            'class' => array('main-menu'),
				        )
				        )));
				        
				        
$out.='</div>';
#$out.=$call;
return $out;

}
function _advert_recursive_tree($menu,$data=null)
{

foreach($menu as $k=>$m)
  {
  if($m['parent']==0){$data[$m['tid']]=$m;unset($menu[$k]);}
# pre($m);
  }

  #_advert_recursive_tree($menu,$data);
  
}
function _advert_print_ajax_menu()
{
$sql="SELECT DISTINCT ttd.tid,ttd.name,tth.parent 
FROM `taxonomy_term_data` ttd 
LEFT JOIN taxonomy_term_hierarchy tth ON tth.tid=ttd.tid
LEFT JOIN taxonomy_index ti ON ti.tid=ttd.tid
LEFT JOIN node n ON n.nid=ti.nid
LEFT JOIN node_advert na ON na.nid=n.nid
WHERE ttd.vid=12  ORDER BY tth.parent";
$result=db_query($sql);
while($r=$result->fetchAssoc())
  {
  $menu[]=$r;
  
  }
  $menu=_advert_recursive_tree($menu);
  pre($menu);
}
function advert_draw_sub_menu()
{
if(isset($_GET['tid']))
{
$parents=taxonomy_get_parents_all($_GET['tid']);
$parents=array_reverse($parents);
}

$out='<!--info PANEL bof-->';
  $out.='<div class="advert_menu_switcher">';

    $subcat_rec=db_query("SELECT ttd.* 
				  FROM taxonomy_term_data ttd 
				  LEFT JOIN `taxonomy_term_hierarchy` tth ON tth.tid=ttd.tid WHERE tth.parent=0 AND ttd.vid=12 ORDER BY ttd.weight");
	$call='';			  
    while($subcat=$subcat_rec->fetchObject())
      {
      if($parents[0]->tid)
	{
	if($parents[0]->tid==$subcat->tid)
	  {
	  $call='<script>advert_switch_menu('.$subcat->tid.');</script>';
	  }else{
	  
	  }
	}elseif(empty($call))$call='<script>advert_switch_menu('.$subcat->tid.');</script>';
	
      $out.='<h2 id="maincat'.$subcat->tid.'"><a href="javascript://"  onClick="advert_switch_menu('.$subcat->tid.');">'.$subcat->name.'</a></h2>';
      }
    
$out.='</div>';
$out.= '<h3>КАТЕГОРИИ</h3>';



$out.= '<div id="advert_taxonomy_box"></div>'.$call;
//load search tid
$parents=taxonomy_get_parents_all($_GET['tid']);
$parents=array_reverse($parents);
$js_call='';
if(isset($_GET['tid']))
{

  $js_call.="<script> 
setTimeout(function(){

 
  jQuery('#advert_first_item".$parents[1]->tid."').css('background','#F89F18');
     var url='/bt-form/callback/advert_load_taxonomy/".$parents[1]->tid."';
  jQuery.ajax({type: 'GET',url: url}).done(function( msg ) { 
    jQuery('#advert_subcat_box".$parents[1]->tid."').html(msg);
    
    jQuery('#offers li input').attr('checked',true);
    jQuery('#advert_second_menu input').each(function(){if(this.id.substr(4)==".$parents[2]->tid."){this.checked=true;}});
    load_adverts(".$parents[2]->tid.");
  });
},1000);
    </script>"."\n";
    
}
$out.= $js_call.'</div><!--info PANEL eof-->';
return $out;
}
function _advert_header_content_node()
{
global $user;
$out='<table class="advert_node_lnk" style="width:100%"><tr>
<td><section class="block ym-clearfix">
					
						<label>
						<form action="/adverts" method="GET">
						<input class="ym-searchfield" type="search" placeholder="быстрый поиск..." name="free_text" />
						<input class="ym-searchbutton" type="submit" value="ПОИСК" onClick="load_adverts(0)"/>
						</form>
						</label>
					
				</section></td>
<td><a class="advert_node_lnk_print" href="javascript://" onClick="window.print();">ПЕЧАТЬ</a></td><td>';
if($user->uid){$out.=l('Здравствуйте , '.$user->name,'user',array('attributes'=>array('class'=>'advert_node_lnk_login')));
}else{
$out.=l('ВХОД','user/login',array('attributes'=>array('class'=>'advert_node_lnk_login')));
}
$out.='</td></tr>
</table>';
return $out;
}
function _advert_header_content()
{
global $user;
$out='<table class="advert_node_lnk" style="width:100%"><tr>
<td><section class="block ym-clearfix">
					
						<label>
						<input class="ym-searchfield" type="search" placeholder="быстрый поиск..." value="'.(isset($_GET['free_text'])?$_GET['free_text']:'').'"/>
						<input class="ym-searchbutton" type="button" value="ПОИСК" onClick="load_adverts(0)"/>
						'.((isset($_GET['free_text']))?'<script>load_adverts(0);</script>':'').'
						</label>
					
				</section></td>
<td><a class="advert_node_lnk_print" href="javascript://" onClick="window.print();">ПЕЧАТЬ</a></td><td>';
if($user->uid){$out.=l('Здравствуйте , '.$user->name,'user',array('attributes'=>array('class'=>'advert_node_lnk_login')));
}else{
$out.=l('ВХОД','user/login',array('attributes'=>array('class'=>'advert_node_lnk_login')));
}
$out.='</td></tr>
</table>';
return $out;
}
/**
*Draw adverts main page
*/
function advert_list()
{
//drupal_add_js("http://masonry.desandro.com/js/jquery.infinitescroll.min.js");
//drupal_add_js("http://www.contextllc.com/dev_tools/jQuery/scrollExtend/latest/js/jquery.scrollExtend.js");


$out=_advert_header_content().'<div id="adverts">'._advert_draw_taxonomy_tbl().'</div>';
return $out;
}
/**
*Draw before ajax loading taxonomy tree in content
**/
function _advert_draw_taxonomy_tbl()
{
$taxonomy=taxonomy_get_tree(12, 0, 3,true);
foreach($taxonomy as $t)
  {
  $data[$t->parents[0]][$t->tid]=$t;
  #print $t->parents[0]."<hr>";
  }
  $out='<ul class="tabs">';
  $call='';
  foreach($data[0] as $mcategory)
    {
    if(empty($call))$call="<script>change_advert_cat(".$mcategory->tid.",document.getElementById(\"advert_cat_link".$mcategory->tid."\"))</script>";
    $out.='<li><a href="javascript://" onclick="change_advert_cat('.$mcategory->tid.',this)" id="advert_cat_link'.$mcategory->tid.'">'.$mcategory->name.'</a></li>';
    #$out.='<li>'.l($mcategory->name,'taxonomy/term'.$mcategory->tid).'</li>';
    }
$out.='</ul>'."\n";    


  foreach($data[0] as $mcategory)
    {
  
    $c=round(count($data[$mcategory->tid])/4);
    
    $i=0;
    $out.='<table id="box'.$mcategory->tid.'" class="advert_taxonomy_tbl"><tr>'."\n";
	foreach($data[$mcategory->tid] as $category)
	    {
	   
	    if($i==0)$out.='<td>';
	    $out.='<h3>'.$category->name.'</h3>'."\n";
	    $out.='<ul>'."\n";
	    foreach($data[$category->tid] as $subcategory)
		{
		$out.='<li>'.l($subcategory->name,'taxonomy/term/'.$subcategory->tid).'</li>'."\n";
		}
	    $out.='</ul>'."\n";	
	    if($i==($c-1))
		  {
		  $out.='</td>'."\n";$i=0;
		  }else{
		  $i++;
		  }
	}
	if($i<($c)){$out.='</td>'."\n";}
	$out.='</tr></table><hr>'."\n";
    }
    $out.=$call;
    return $out;
}
function advert_load_taxonomy($tid)
{
#pre(taxonomy_get_children($tid,12));
#$tree=taxonomy_get_tree(12,$tid);
#$city =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);
 global $infopark;    
$city=$infopark->get_city_by_url();
	$current_city=$city['tid'];
$parents=taxonomy_get_parents($tid);

if(count($parents)==0)
{
$tree=taxonomy_get_children($tid,12);
#pre($tree);
$out='<ul class="advert_first_menu">';

foreach($tree as $t)
{
$sql="SELECT count(DISTINCT n.nid) as counter 
FROM taxonomy_term_hierarchy tth 
LEFT JOIN taxonomy_term_data ttd ON ttd.tid=tth.tid 
LEFT JOIN taxonomy_index ti ON ti.tid=tth.tid 
LEFT JOIN node n ON n.nid=ti.nid
LEFT JOIN taxonomy_index ti1 ON ti1.nid=n.nid 
LEFT JOIN node_advert na ON na.nid=n.nid 
LEFT JOIN node_advert_dates nad ON nad.nid=n.nid 
INNER JOIN advert_offers_node aon ON aon.nid=n.nid
WHERE tth.parent=".db_escape_field($t->tid)." AND n.type='advert' and n.status=1 AND  na.body!='' AND nad.public_date='".date("Y-m-d")."'".(($current_city)?' AND ti1.tid='.$current_city:"");

#print $sql."<hr>";
$n=db_query($sql)->fetchObject();
#pre($n);
#print $sql."<hr>";
if($n->counter)
{
$out.='<li id="advert_first_item'.$t->tid.'"><label   for="menu'.$t->tid.'"><a href="javascript://" onclick="open_advert_menu_box('.$t->tid.');">'.$t->name.'</a><em>('.$n->counter.')</em></label>'."\n";
$out.='<div id="advert_subcat_box'.$t->tid.'" class="advert_subcat_box"></div>';
$out.='</li>';
}
}
$out.='</ul>';
}else{

#$tree=taxonomy_get_children($tid,12);
  $sql="SELECT DISTINCT ao.* 
	  FROM taxonomy_term_hierarchy tth
	  INNER JOIN node_advert_terms_taxonomy natt ON natt.tid=tth.tid
	INNER JOIN node_advert_terms nat ON nat.id=natt.node_advert_terms_id
      LEFT JOIN advert_offers_code aoc ON aoc.code=nat.code
      LEFT JOIN advert_offers ao ON ao.id=aoc.oid
      INNER JOIN advert_offers_node aon ON aon.oid=aoc.oid
	WHERE tth.parent=".$tid;
	#print $sql."<hr>";
    $sql_offers=db_query($sql);
	
$out.='<ul class="" id="offers'.$t->tid.'">'."\n";
while($offer=$sql_offers->fetchObject())
  {
  $out.='<LI><input type="checkbox" name="offers['.$offer->id.']" id="offers['.$offer->id.']" onChange="jQuery(\'.all\').attr(\'checked\',false);load_adverts('.$tid.');">'.$offer->name.'</li>'."\n";
  }
  $out.='</ul>';
$sql1="select ttd.tid,ttd.name
FROM taxonomy_term_hierarchy tth 
LEFT JOIN taxonomy_term_data ttd ON ttd.tid=tth.tid
INNER JOIN taxonomy_index ti ON ti.tid=ttd.tid
INNER JOIN node n ON n.nid=ti.nid
LEFT JOIN taxonomy_index ti1 ON ti1.nid=n.nid 
INNER JOIN node_advert_dates nad ON nad.nid=n.nid
WHERE tth.parent=".Q((int)$tid)." AND n.type='advert' AND n.status=1 AND nad.public_date='".date("Y-m-d")."'
".(($current_city)?" AND ti1.tid=".$current_city." ":"")."
GROUP BY ttd.tid,ttd.name
ORDER BY ttd.weight";
#print $sql1;
$sql_tree=db_query($sql1);
#pre($tree);
$out.='<ul class="advert_second_menu" id="advert_second_menu'.$t->tid.'">'."\n";
#foreach($tree as $t1)
while($t1=$sql_tree->fetchObject())
{

$out.='<LI><span><label for="menu'.$t1->tid.'"><input type="checkbox"  id="menu'.$t1->tid.'" onChange="jQuery(\'.all\').attr(\'checked\',false);load_adverts('.$tid.');">'.$t1->name.'</label></span></li>'."\n";
}	
$out.='</ul>';
}
#print _advert_draw_taxonomy_tree($tree,$tid);
#pre($tid."XXXX");
die($out);
}
function advert_load_adverts($tid)
{
	$offset=0;
	if(strstr($tid,"|"))
	{
	$arr=explode("|",$tid);
	$tids=$arr[0];
	$ar_tids=explode(",",$tids);
		foreach($ar_tids as $t)
		  {
		  if(!empty($t))$new_tids[]=$t;
		  }
	$new_tids=array_unique($new_tids);
	$tids=implode(",",$new_tids);
	$offers=explode(",",$arr[1]);
	$new_offers=false;
		foreach($offers as $o)
		  {
		  if(!empty($o))$new_offers[]=$o;
		  }
	$offers=implode(",",$new_offers);
	if($offers==0)$offers=array();
	if(isset($arr[2]))$offset=$arr[2];
	else $offset=0;
        
        global $infopark;
        $city=$infopark->get_city_by_url();
	#$city =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);	
	$current_city=$city['tid'];
	
	if($offset==0)print advert_print_reccomended($tids,$offers,$current_city);

	print advert_print_fresh($tids,$offers,$offset,$current_city);
	
	}/*else{
	
	$offers=array();
	
	if($offset==0)print advert_print_reccomended4all($tid,$offers);
	print advert_print_fresh4all($tid,$offers,$offset);
	}*/


die("");
}/*
function _advert_draw_logo()
{
return '<div class="logon"><a href="http://www.infopark.com.ua"><img src="/misc/images/logo.png" border=0 alt="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша Харькова. Билеты на концерты" title="Афиша: события, концерты, спектакли, галереи | Инфопарк афиша Харькова. Билеты на концерты"></a></div>';
}*/
function advert_compromise_get_citydomain($domain)
{
//is temporary hack
#$domain='www.kiev.infopark.com.ua';
global $infopark;
return $infopark->get_city_by_url();
/*$city=db_select("citydomain","c")->fields("c")->condition('url','http://'.$domain)->execute()->fetchAssoc();
if($city['tid'])return $city;
else return false;*/
}
/**
*Main ajax function
*/
function advert_print_fresh($tids,$offers,$offset=0,$current_city=0)
{

$status_id=0;
$out='';
#if($offset)$out.='<h1>IS AJAX</h1>';

if($tids)
{
$tt=explode(",",$tids);

foreach($tt as $t)
{
$tids_array[]=Q((int)$t);
}
}

$oo=explode(",",$offers);
foreach($oo as $o){$offers_array[]=Q((int)$o);}

$sql_count="SELECT count(DISTINCT n.nid) as total 
FROM taxonomy_index ti 
LEFT JOIN node n ON n.nid=ti.nid 
LEFT JOIN taxonomy_index ti1 ON ti1.nid=n.nid
LEFT JOIN advert_offers_node aon ON aon.nid=n.nid
INNER JOIN node_advert na On na.nid=n.nid 
INNER JOIN node_advert_dates napd ON napd.nid=na.nid 
WHERE n.type='advert' AND n.status=1 AND na.field_type='fresh' AND  na.body!='' AND napd.public_date='".date('Y-m-d')."' 
".(count($tids_array)?"and ti.tid IN (".implode(",",$tids_array).")":"")."
".(($current_city)?"AND ti1.tid=".$current_city." ":"")."
".(!empty($_GET['free_text'])?" AND (n.title LIKE '%".Q($_GET['free_text'],1)."%'  OR na.body LIKE '%".Q($_GET['free_text'],1)."%')":"")."
".(count($offers_array)?"AND aon.oid IN (".implode(",",$offers_array).")":"");

$counter_rec=db_query($sql_count);
$counter=$counter_rec->fetchObject();
if($offset==0)
{
$out.='<div class="advert_counter">НАЙДЕНО <span>'.$counter->total.'</span> ОБЬЯВЛЕНИЙ</div>';
 $ar=explode("|",$_SERVER['REQUEST_URI']);

}
#$out.='<h1>'.$offset.'</h1>';
if($counter->total)
{
$sql="SELECT DISTINCT n.*,na.body as teaser
FROM taxonomy_index ti 
INNER JOIN node n ON n.nid=ti.nid 
LEFT JOIN taxonomy_index ti1 ON ti1.nid=n.nid
LEFT JOIN advert_offers_node aon ON aon.nid=n.nid
INNER JOIN node_advert na On na.nid=n.nid 
INNER JOIN node_advert_dates napd ON napd.nid=na.nid 
WHERE n.type='advert' 
AND n.status=1 AND na.field_type='fresh' AND na.body!='' AND napd.public_date='".date('Y-m-d')."' 
".(count($tids_array)?"and ti.tid IN (".implode(",",$tids_array).")":"")."
".(count($offers_array)?"AND aon.oid IN (".implode(",",$offers_array).")":"")."
".(($current_city)?"AND ti1.tid=".$current_city." ":"")."
".(!empty($_GET['free_text'])?" AND (n.title LIKE '%".Q($_GET['free_text'],1)."%'  OR na.body LIKE '%".Q($_GET['free_text'],1)."%')":"")."
order by napd.public_date
LIMIT 20 OFFSET ".$offset;
#print $sql."<hr>";
$nodes_rec=db_query($sql);
#
#$out='<table border=1><tr>';
$c=0;
while($node=$nodes_rec->fetchObject())
  {
  $nodes[]=$node;
  $columns[$c][]=$node;
    $c++;
    if($c==4)$c=0;
  }
  #pre($columns);
 if(count($nodes))
 {
  //only one
 if($offset==0)
	{
	if($_COOKIE['advert_view']=='list')$out.='<div class="advert_row" id="columns_in_row">';
	else $out.='<div class="advert_row" id="columns">';
	}
  foreach($columns as $column)
    {
    foreach($column as $node)
      {
  
      #$out.='<div class="one_short_item">';
	  if($_COOKIE['advert_view']=='list')$out.='<div class="pin" style="display:block;width:95%;">';
	  else $out.='<div class="pin">';
      $out.=_advert_draw_node($node,'advert_node');
    $out.='</div>';
      }
  
      
    }
   if($offset==0){$out.='</div>';}

 if(($offset==0)&&($counter->total>20))$out.='<div class="down" onClick="load_adverts_next(20);"></div>';
 }
 }
 
  return $out;
}

function advert_print_reccomended($tids,$offers,$current_city=0)
{
if($tids)
{
$tt=explode(",",$tids);

foreach($tt as $t)
{
$tids_array[]=Q((int)$t);
}
}
#pre($tids_array);
$oo=explode(",",$offers);

foreach($oo as $o){$offers_array[]=Q((int)$o);}
$sql="SELECT DISTINCT n.*,na.body as teaser
FROM taxonomy_index ti 
LEFT JOIN taxonomy_term_hierarchy tth ON tth.tid=ti.tid
LEFT JOIN node n ON n.nid=ti.nid 
LEFT JOIN taxonomy_index ti1 ON ti1.nid=n.nid 
LEFT JOIN advert_offers_node aon ON aon.nid=n.nid
INNER JOIN node_advert na On na.nid=n.nid 
INNER JOIN node_advert_dates napd ON napd.nid=na.nid 
WHERE n.type='advert' AND n.status=1 AND na.field_type='reccomended' AND napd.public_date='".date('Y-m-d')."' 
".(count($offers_array)?"AND aon.oid IN (".implode(",",$offers_array).")":"")."
".(count($tids)?"and ti.tid IN (".implode(",",$tids_array).")":"")."
".(($current_city)?"AND ti1.tid=".$current_city." ":"")."
".(!empty($_GET['free_text'])?" AND (n.title LIKE '%".Q($_GET['free_text'],1)."%'  OR na.body LIKE '%".Q($_GET['free_text'],1)."%')":"")."
order by napd.public_date,n.created limit 4";
#print $sql;
$nodes=db_query($sql);
$out='<table style="width:100%"><tr>';
while($node=$nodes->fetchObject())
  {
  #pre($node);
  $out.='<td>'._advert_draw_node($node,'advert_reccomended_node').'</td>';
  #pre($node);
  }
$out.='</tr></table>';  
$out.='<div class="reccomend_advert_text"><a href="javascript://" id="advert_view_btn" onCLick="chg_advert_dsg(this)" style="float:left">смотреть списком</a><a href="#">Как поднять сюда свое обьявление</a></div>';
return $out;
}
function _advert_draw_node($node,$class='advert_reccomended_node')
{
if(!$node->advert)$node=_advert_get_node($node);
$offers=$node->advert['offers'];
$out='<div class="'.$class.'">';
if(isset($node->files))
  {
  $pic_file=array_shift($node->files);
  
$options = array(
  'style_name' => 'advert',
  'alt' => 'Alternative Text',
  'path' => $pic_file['uri']
);

  $out.=theme('image_style', $options);
  }
  $taxonomy=taxonomy_term_load_multiple($node->taxonomy);
  foreach($taxonomy as $t)
    {
    if($t->vid==6)$out.=$t->name;
    }
if(!empty($status_name))$out.='<p>'.$status_name."</p>";
$out.='<h5>'.mb_substr($node->title,0,40).'</h5>';
$out.='<h3>';
#pre($node->advert['field_price']);
if($node->advert['field_price'])
{
$out.=$node->advert['field_price']." грн.";
}
if($node->advert['field_price_optom'])
{
$out.="Цена оптовая ".$node->advert['field_price_optom']." грн.";
}
if($node->advert['field_price_from'])
{
$out.="Цена от ".$node->advert['field_price_from'].(($node->advert['field_price_end'])?" до ".$node->advert['field_price_end']:"")." грн.";
}
#pre($node);
$out.='</h3>';
$out.='<p>'.$node->teaser.'</p>';
$out.='</div>';
return l($out,'node/'.$node->nid,array('html'=>true));
}
/**
*draw nodes list for advert taxonomy pages , need for SEO 
**/
function advert_print_taxonomy_nodes($term)
{
/*
$sql="SELECT DISTINCT n.*,na.* 
FROM taxonomy_index ti 
LEFT JOIN node n ON n.nid=ti.nid 
INNER JOIN node_advert na On na.nid=n.nid 
INNER JOIN node_advert_dates napd ON napd.nid=na.nid 
WHERE n.type='advert' AND na.field_type='fresh' AND napd.public_date='".date('Y-m-d')."' and ti.tid=".$term->tid." 
order by napd.public_date,n.created limit 4";
*/
$sql="SELECT DISTINCT n.*,na.*,frb.body_summary as teaser
FROM taxonomy_index ti 
LEFT JOIN node n ON n.nid=ti.nid 
LEFT JOIN field_data_body frb ON frb.entity_id=n.nid
INNER JOIN node_advert na On na.nid=n.nid 
INNER JOIN node_advert_dates napd ON napd.nid=na.nid 
WHERE n.type='advert' AND napd.public_date='".date('Y-m-d')."' and ti.tid=".$term->tid." 
order by na.field_type,napd.public_date,n.created limit 4";
print $sql;
$nodes=db_query($sql);
$out='<table><tr>';
while($node=$nodes->fetchObject())
  {
  
  $out.='<td><div>'.l($node->title,'node/'.$node->nid).'<p>'.$node->teaser.'</p></div></td>';
  #pre($node);
  }
$out.='</tr></table>';  
return $out;
}
/*
function advert_menu_alter(&$items) {

  if (!empty($items['taxonomy/term/%taxonomy_term'])) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'advert_term_page';
  $items['taxonomy/term/%taxonomy_term']['module']='advert';
  $items['taxonomy/term/%taxonomy_term']['file']='advert_compromise.inc';
  
  #pre($items,1);

    
  }
  return $items;
}
*/
/**
* Roman alternative for taxonomy_term_page, inserted via hack to taxonomy_term_page
**/
function advert_term_page($term) {
#kolichestvo na stranicu
$count=12;

  drupal_set_title($term->name);

  $current = (object) array(
    'tid' => $term->tid,
  );
  // @todo This overrides any other possible breadcrumb and is a pure hard-coded
  //   presumption. Make this behavior configurable per vocabulary or term.
  
  $breadcrumb = array();
  while ($parents = taxonomy_get_parents($current->tid)) {
    $current = array_shift($parents);
    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
  }
  $breadcrumb[] = l(t('Home'), NULL);
  $breadcrumb = array_reverse($breadcrumb);
  drupal_set_breadcrumb($breadcrumb);
  drupal_add_feed('taxonomy/term/' . $term->tid . '/feed', 'RSS - ' . $term->name);

  // Set the term path as the canonical URL to prevent duplicate content.
  $uri = entity_uri('taxonomy_term', $term);
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);

  $build['term_heading'] = array(
    '#prefix' => '<div class="term-listing-heading">',
    '#suffix' => '</div>',
    'term' => taxonomy_term_view($term, 'full'),
  );
  $query = db_select('taxonomy_term_data', 'ttd');
  $query->join('taxonomy_term_hierarchy','tth','tth.parent=ttd.tid');
 $query->join('taxonomy_index','ti','ti.tid=tth.tid OR ti.tid=tth.parent');
 $query->join('node','n','n.nid=ti.nid');
 $query->join('node_advert','na','na.nid=n.nid');
 $query->join('node_advert_dates','napd','napd.nid=na.nid');

 $query->condition('n.type','advert')->condition('n.status',1)->condition('napd.public_date',date('Y-m-d'));
 $or = db_or();
 $or->condition('tth.tid',$term->tid);
 $or->condition('tth.parent',$term->tid);
 $query->condition($or);
 
  $count_query = clone $query;
$count_query->addExpression('COUNT(n.nid)');
 $query->fields('n');
 $query->fields('na',array('body'));
 $query = $query->extend('PagerDefault');
 $query = $query->limit($count);
  $query->setCountQuery($count_query);
 $query->orderBy('na.field_type')->orderBy('napd.public_date')->orderBy('n.created');

 $nid_rec=$query->execute();

while($node=$nid_rec->fetchObject())
{
$nodes[]=$node;
}
  if ($nodes) {
  

  
    #$nodes = node_load_multiple($nids);    
#pre($nodes,1);
$build += node_view_multiple($nodes);



    $build['nodes']['#prefix']='<div class="advert_row" id="columns">';
        
   
    $build['nodes']['#suffix']='</div><script>advert_taxonomy_masonry();</script>';
#    $build['nodes']['#weight']=6;
	  $build['pager'] = array(
#    '#prefix'=>'<div style="position:relative;">',
    #'#suffix'=>'</div>',
      '#theme' => 'pager',
#      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '<p>',
      '#markup' => t('There is currently no content classified with this term.'),
      '#suffix' => '</p>',
    );
  }
  
  return $build;
}
/**
*Draw taxonomy simple html menu for advert-taxonomy
**/
function advert_taxonomy_static_tree($tid)
{
$term=taxonomy_term_load($tid);
if($term->vid!=12)return null;
$pp=taxonomy_get_parents_all($tid);
$pp=array_reverse($pp);
$older_tid=$pp[0]->tid;
foreach($pp as $p){ $parents[]=$p->tid; }
#$parents=array_keys($pp);
#pre($parents);

$taxonomy=taxonomy_get_tree($term->vid, 0, 3,true);

foreach($taxonomy as $t)
  {
  $data[$t->parents[0]][$t->tid]=$t;
  #print $t->parents[0]."<hr>";
  }
 # $out='<div style="display:block;margin:70px 0;">';
   $out='';
  foreach($data[0] as $mcategory)
    {
	#print $pp."<hr>";
    #$out.='<h2><label>'.$mcategory->name.'</label></h2>';
    $out.='<ul>';
    foreach($data[$mcategory->tid] as $category)
	    {
	   #print in_array($category->tid,$parents)."<hr>";
	 #
	    $out.='<li'.(!in_array($category->tid,$parents)?' style="display:none;"':'').'>'.l($category->name,'taxonomy/term/'.$category->tid);
	    $out.='<ul>'."\n";
	    if($data[$category->tid])
	    foreach($data[$category->tid] as $subcategory)
		{
		$out.='<li>'.l($subcategory->name,'taxonomy/term/'.$subcategory->tid).'</li>'."\n";
		}
	    $out.='</ul>
	    </li>'."\n";	

	    }
    $out.='</ul>';
    #$out.='<li>'.l($mcategory->name,'taxonomy/term'.$mcategory->tid).'</li>';
    }
#$out.='</div>'."\n";    

$out.=''."\n";  
  	
    
    return $out;
}
function _advert_draw_field_form($node)
{
$terms=taxonomy_term_load_multiple($node->taxonomy,array('vid'=>12));
#pre($terms);
$term=array_shift($terms);
$c=db_select("node_advert_terms_taxonomy","natt");
$c->join("node_advert_terms","nat","nat.id = natt.node_advert_terms_id");
$c->fields('nat');
$b=$c->condition('natt.tid',$term->tid)->execute()->fetchObject();

unset($node->custom_fields['field_phone']);


$type_rec=db_select('advert_fields_type','aft')->fields('aft')->condition('type',$b->code)->orderby("weight")->execute();
$out='<div id="advert_node_left_search"><input type="hidden" id="hidden_tid" value="'.$term->tid.'">';
while($type=$type_rec->fetchObject())
  {
  #pre($node->custom_fields[$type->field]->value);
  $out.='<div><h5>'.$type->name.'</h5>
  <select name="'.$type->field.'"><option value="0">--нет--</option>';  
  
  $fields_rec=db_select('advert_fields','af')->fields('af')->condition('field',$type->field)->condition('parent',0)->orderby("name")->execute();
	while($field=$fields_rec->fetchObject())
	  {
	    $out.='<option value="'.$field->id.'" '.(($node->custom_fields[$type->field]->value)&&($node->custom_fields[$type->field]->value==$field->id)?'selected':'').'>'.$field->name.'</option>';
	  }
  $out.='</select></div>';
  #pre($type);
  }
  $out.='<input type="button" value="Поиск" onClick="advert_node_left_search_submit();"></div>';
return $out;
}
/*фильтр галлерей, мелкие айконы*/
function _advert_compromise_gallery_filter($nid)
{

$query=db_select("node","n");
$query->join("field_data_media_gallery_media","m","m.entity_id=n.nid");
$query->join("file_managed","f","f.fid=m.media_gallery_media_fid");
		$query->fields('n',array('nid','title','created'))
		->fields('f',array('fid','filename','uri'))
		->condition('n.type','media_gallery')
		->condition('n.status',1)
		->condition('f.status',1)
		->condition('f.type','image')
		->groupby('n.nid')
		->orderby("n.created","DESC");
$gallerys=$query->execute()->fetchAll();

$out="<div class='small_gall_list'>";
$out="<h3>Другие галереи</h3>
<ul class='gallery_other_ul'>";
$i=0;
foreach($gallerys as $gal)
	{
	#if($i==0)$out.='<div class="gall_row">';
	if($nid==$gal->nid)$class="active_pic";
	else $class="";
	$out.= '<li>'.l("<img src='".image_style_url('media_gallery_thumbnail', $gal->uri)."' height='50'>","node/".$gal->nid,array('html'=>true,'attributes'=>array('title'=>$gal->title,'class'=>array($class)))).' '.l($gal->title,'node/'.$gal->nid,array('attributes'=>array('title'=>date('d.m.Y',$gal->created),'class'=>array('gallery_other_a')))).'</li>';
	#if($i==11){$i=0;$out.='</div>';}
	#else $i++;
	}
	#if(($i<11)&&($i!=0))$out.="</div>";
$out.="</ul></div>";
return $out;
}
/*фильтр галлерей -  фото, мелкие айконы*/
function _advert_compromise_gallery_photo_filter($nid)
{
$fid=arg(3);

$query=db_select("node","n");
$query->join("field_data_media_gallery_media","m","m.entity_id=n.nid");
$query->join("file_managed","f","f.fid=m.media_gallery_media_fid");
		$query->fields('f',array('fid','filename','uri'))
		->condition('n.type','media_gallery')
		->condition('n.status',1)
		->condition('n.nid',$nid)
		->condition('f.status',1)
		->condition('f.type','image')
#		->groupby('n.nid')
		->orderby("n.created");
$photos=$query->execute()->fetchAll();
$out="<div class='small_gall_list'>";
$out="<h3>Другие фото</h3>";
$i=0;
foreach($photos as $gal)
	{
	if($i==0)$out.='<div class="gall_row">';
	if($fid==$gal->fid)$class="active_pic";
	else $class="";
	$out.= l("<img src='".image_style_url('media_gallery_thumbnail', $gal->uri)."' height='50'>","media-gallery/detail/".$nid."/".$gal->fid,array('html'=>true,'attributes'=>array('title'=>$gal->filename,'class'=>array($class))));
	$i++;
	if($i==12){$i=0;$out.='</div>';}
	
	}
	#print $i;
	if($i<12)$out.="</div>";
	
$out.="</div>";
return $out;
}
/*фильтр галлерей по месяц год, мелкие айконы*/
function _advert_compromise_gallery_ddmm_filter()
{
global $conf;
$dbquery=db_query("SELECT DISTINCT FROM_UNIXTIME(created,'%m%Y') as d FROM node WHERE type='media_gallery' AND status=1 ORDER BY created DESC");

$out='<ul class="gall_ddmm_list">';
foreach($dbquery as $q)
{

$out.='<li>'.l($conf['month_namez'][floor(substr($q->d,0,2))-1].' '.substr($q->d,2),'gallery_period/'.$q->d).'</li>';
#$out.='<li>'.l($conf['month_namez'][date('n',strtotime($q->d))-1].' '.date('Y',strtotime($q->d)),'gallery_period/'.date('dmY',strtotime($q->d))).'</li>';
#pre($q);
}
$out.='</ul>';
return $out;
}
function advert_compr_gallery_ddmm_list($d)
{
global $conf;
#$t=strtotime(substr($d,4).'-'.substr($d,2,2).'-01');
$query=db_select("node","n");
$query->join("field_data_media_gallery_media","m","m.entity_id=n.nid");
$query->join("file_managed","f","f.fid=m.media_gallery_media_fid");
		$query->fields('n',array('nid','title','created'))
		->fields('f',array('fid','filename','uri'))
		->condition('n.type','media_gallery')
		->condition('n.status',1)
		->condition('f.status',1)
		->condition('f.type','image')
		->groupby('n.nid')
		->orderby("n.created","DESC");
$query->where("FROM_UNIXTIME(created, '%m%Y') = :date", array(':date' => $d));		
$gallerys=$query->execute()->fetchAll();
#<img class="stack-image" src="/sites/all/modules/media_gallery/images/stack_bg.png">


$out='<h1>'.$conf['month_namez'][floor(substr($d,0,2))-1].' '.substr($d,2).'</h1>';
$out.='<div id="column gal_thumb">';
foreach($gallerys as $gal)
	{
	$out.='<div class="pin">'.l("<img src='".image_style_url('media_gallery_thumbnail', $gal->uri)."' width='450' height='450'>","node/".$gal->nid,array('html'=>true,'attributes'=>array('title'=>$gal->title,'class'=>array('media-gallery-thumb')))).'</div>';
	}
$out.='</div>';
return $out;
}

function _advert_comp_reccomended_events_block()
{
global $infopark;    
#$cc =advert_compromise_get_citydomain($_SERVER['HTTP_HOST']);
$cc=$infopark->get_city_by_url();
$current_city=$cc['tid'];
$query = db_select('node', 'n');	
		$query->leftJoin('field_data_field_schedule_event', 's_event', 'n.nid = s_event.entity_id');
		$query->leftJoin('field_data_field_schedule_start', 's_start', 'n.nid = s_start.entity_id');
		$query->leftJoin('field_data_field_schedule_place', 's_place', 'n.nid = s_place.entity_id');
		$query->leftJoin('node', 'place_node', 'place_node.nid = s_place.field_schedule_place_nid');
		$query->leftJoin('field_data_field_place_city', 'place_city', 'place_city.entity_id = s_place.field_schedule_place_nid');
		$query->leftJoin('node', 'event_node', 's_event.field_schedule_event_nid = event_node.nid');
		$query->leftJoin('taxonomy_index', 'ti', 'event_node.nid = ti.nid');
		$query->leftJoin('field_data_field_event_ticket_id', 'ticket_id', 'event_node.nid = ticket_id.entity_id');
		$query->leftJoin('field_data_field_event_description', 'event_desc', 'event_node.nid = event_desc.entity_id');

		$query->leftJoin('field_data_field_event_thumbnail', 'nthumbnail', 'event_node.nid = nthumbnail.entity_id');
		$query->leftJoin('file_managed', 'f', 'nthumbnail.field_event_thumbnail_fid = f.fid');
		$query->leftJoin('url_alias', 'ua', "ua.source like concat('node/', event_node.nid)");

		$query->fields('event_node', array('title', 'nid'))->fields('event_desc',array('field_event_description_value'));

		#	->fields('s_start', array('field_schedule_start_value'))
		#	->fields('f', array('uri'))
		#	->fields('ua')
		#	->fields('place_city', array('field_place_city_tid'))
		#	->fields('s_place', array('field_schedule_place_nid'))
		#	->fields('place_node', array('title'))
		#	->fields('ticket_id', array('field_event_ticket_id_value'))
		#	->fields('event_desc',array('field_event_description_value'))
		#	->fields('ti', array('tid'));

			#->groupBy('title')
			#$query->groupBy('s_start.field_schedule_start_value');
			$query->groupBy('event_node.title');
			#$query->groupBy('s_start.field_schedule_start_value');
			$query->orderBy('DATE_FORMAT(s_start.field_schedule_start_value,\'%Y%m%d\')', 'ASC')
			
			->orderBy('s_start.field_schedule_start_value', 'ASC')
			->condition('n.type', 'schedule')
			->condition('event_node.type', 'event');
			if($current_city)$query->condition('place_city.field_place_city_tid',$current_city);
			
			$query->condition('ti.tid',111);
			
			$query->where("DATE_FORMAT(s_start.field_schedule_start_value,'%Y%m%d') >= (:date)",array(':date'=>date('Ymd')));
			$query->range(0,10);
	$events = $query->execute()->fetchAll();
	$out='<div class="reccommended_events_block">
	<h3>Рекомендованные события</h3>
	<ul>';
	foreach($events as $event)
		{
		$out.='<li>'.l($event->title,'node/'.$event->nid,array('attributes'=>array('title'=>substr(strip_tags($event->field_event_description_value),0,150)))).'</li>';
		}
	$out.='</ul></div>';	
	return $out;
}
?>